package cn.wenhaha.app.job.service;

import cn.hutool.core.map.MapUtil;
import cn.wenhaha.app.job.manager.SyncMappingJob;
import cn.wenhaha.common.bean.JobStartEvent;
import cn.wenhaha.common.config.GlobalApp;
import cn.wenhaha.common.db.bean.SysMapping;
import cn.wenhaha.job.DynamicJob;
import cn.wenhaha.job.ScheduleDynamicUtil;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 定时任务
 * --------
 *
 * @author ：wyndem
 * @Date ：Created in 2022-10-30 20:58
 */
@Service
public class JobTaskService {

    @Resource
    private SysMapping sysMapping;


    /**
     * <p>
     *    启动时查看是否有启动的Mapping
     * </p>
     * @Author: Wyndem
     * @DateTime: 2022-10-30 20:59
     */
    @EventListener({JobStartEvent.class})
    public void loadJob(){
        if (!GlobalApp.isLoadConfigDb()){
            return;
        }
        List<SysMapping> sysMappings = sysMapping.queryActivation();
        sysMappings.forEach(sysMapping -> {
            DynamicJob dynamicJob = new DynamicJob(sysMapping.getCron(),
                    Long.parseLong(sysMapping.getId()),  new SyncMappingJob(), sysMapping.getCreateBy());
            dynamicJob.setData(MapUtil.builder(SysMapping.class.getName(),(Object)sysMapping).build());
            ScheduleDynamicUtil.addJob(dynamicJob);
        });


    }

}
